package com.itheima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.mededia.pojo.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.itheima.aliyun.scan.GreenScan;
import com.itheima.aliyun.scan.ScanResult;
import com.itheima.common.constants.message.PublishArticleConstants;
import com.itheima.common.exception.CustException;
import com.itheima.feigns.AdminFeign;
import com.itheima.wemedia.mapper.WmNewsMapper;
import com.itheima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private GreenScan greenScan;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Value("${file.oss.web-site}")
    String webSite;

    @Override
    public void autoScanWmNews(Integer id) {
        //1. 根据文章id 查询文章
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
            log.error("自动审核失败  id为空");

        }
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            log.error("自动审核失败  文章不存在");
        }
        // 2. 判断文章状态是否为待审核状态
        Short status = wmNews.getStatus();
        if (status == WmNews.Status.SUBMIT.getCode()) {//待审核状态
            // 抽取出文章中 所有的文本内容 和 所有的图片url集合    Map<String,Object>  content 内容   images List<String>
            Map<String, Object> contentAndImage = handleTextAndImages(wmNews);
            // 3.1  敏感词审核    失败   修改文章状态(2)
            String content= (String) contentAndImage.get("content");
            Boolean flagDFA = handleSensitive(content,wmNews);
            if (!flagDFA) return;
            log.info("自定义敏感词审核通过");
            //3.2  阿里云的文本审核   失败  状态2  不确定 状态3
            Boolean flagAliyun = handleTextScan(content,wmNews);
            if (!flagAliyun) return;
            log.info("阿里云内容审核通过");
            // 3.3  阿里云的图片审核   失败  状态2  不确定 状态3
            List<String> images = (List<String>)contentAndImage.get("images");
            if (images!= null){
                boolean flagImages = handeleImagesScan(images,wmNews);
                if (!flagImages) return;
                log.info("阿里云图片审核通过");
            }
        }
        // 4. 判断文章发布时间是否大于当前时间   状态 8
        updateWmNews(wmNews,WmNews.Status.SUCCESS.getCode(),"审核成功");
        //TODO 5. 通知定时发布文章
        //5. 通知定时发布文章
        // 发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        // 当前时间
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;
        // 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , (message)->{                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());
    }

    private boolean handeleImagesScan(List<String> images, WmNews wmNews) {
        boolean flag =true;
        try {
            ScanResult scanResult = greenScan.imageUrlScan(images);
            String suggestion = scanResult.getSuggestion();
            switch (suggestion){
                case "block":
                    updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"图片中有违规内容，审核失败");
                    flag = false;
                    break;
                case "review":
                    updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"图片中有不确定内容，转为人工审核");
                    flag = false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云图片审核出现异常 , 原因:{}",e.getMessage());
            updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"图片中有不确定内容，转为人工审核");
            flag=false;
        }
        return flag;

    }

    @Autowired
    private AdminFeign adminFeign;

    private Boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag  = true;
        //获取敏感词列表
        List<String> senstives = adminFeign.sensitives().getData();

        SensitiveWordUtil.initMap(senstives);
        Map<String, Integer> result = SensitiveWordUtil.matchWords(content);
        if (result.size()>0){
            updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"内容含有敏感词"+ result);
            flag=false;
        }
        return flag;
    }

    private Boolean handleTextScan(String content, WmNews wmNews) {
        if (StringUtils.isBlank(content)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
            log.error("自动审核文章失败   文章内容为空");
        }
        boolean flag =true;

        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            if (!scanResult.isSuccess()){
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
                log.error("阿里云自动审核异常");
            }
            String suggestion = scanResult.getSuggestion();
            switch (suggestion){
                case "block":
                    updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"文本中有违规内容，审核失败");
                    flag = false;
                    break;
                case "review":
                    updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"文本中有不确定内容，转为人工审核");
                    flag = false;
                    break;

            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云文本审核出现异常 , 原因:{}",e.getMessage());
            updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"阿里云内容服务异常，转为人工审核");
            flag = false;
        }
        return flag;
    }

    private void updateWmNews(WmNews wmNews, short code, String s) {
        wmNews.setStatus(code);
        wmNews.setReason(s);
        wmNewsMapper.updateById(wmNews);
    }

    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        if (StringUtils.isBlank(wmNews.getContent())) {
            log.error("自动审核文章失败    文章内容为空");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        String content = wmNews.getContent();
        List<Map> mapList = JSON.parseArray(content, Map.class);
        // 1. 抽取文章中所有文本  中间使用_hmtt_拼接  防止前面最后一个字和后面第一个字连接使自动审核误判
        String collect = mapList.stream()
                                .filter(m -> m.get("type").equals("text"))
                                .map(x -> (String) x.get("value"))
                                .collect(Collectors.joining("_hmtt_"));
        // 拼接标题
        collect=collect+"_hmtt_"+wmNews.getTitle();
        //2. 抽取文章中所有图片   content :  全路径       images :  文件名称  + 访问前缀
        List<String> images = mapList.stream().filter(m -> m.get("type").equals("image"))
                .map(x -> (String) x.get("value"))
                .collect(Collectors.toList());
        if (StringUtils.isNotBlank(wmNews.getImages())){
            String wmNewsImages = wmNews.getImages();
            String[] split = wmNewsImages.split(",");
            List<String> urls = Arrays.stream(split).map(url -> webSite + url).collect(Collectors.toList());
            images.addAll(urls);
        }
        List<String> imageList = images.stream().distinct().collect(Collectors.toList());
        HashMap<String, Object> map = new HashMap<>();
        map.put("content",collect);
        map.put("images",imageList);
        return map;

    }
}
